<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <ShipmentSearchForm v-show="showSearch" :query-params="queryParams" @search="handleQuery" @reset="resetQuery" />

    <!-- 工具栏 -->
    <ShipmentToolbar :single="single" :multiple="multiple" :delete-disabled="deleteDisabled"
      :show-search.sync="showSearch" :export-loading="exportLoading" @add="handleAdd" @update="handleUpdate"
      @delete="handleDelete" @export="handleExport" @refresh="getList" />

    <!-- 数据表格 -->
    <ShipmentTable :loading="loading" :shipment-list="shipmentList" @selection-change="handleSelectionChange"
      @detail="handleDetail" @delete="handleDelete" @bind-locator="handleBindLocator"
      @unbind-locator="handleUnbindLocator" @sort-change="handleSortChange" />

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 新增/修改抽屉 -->
    <ShipmentFormDrawer :visible.sync="open" :title="title" :form="form" :rules="rules" :mode="mode"
      @submit="submitForm" @cancel="cancel" />

    <!-- 详情抽屉 -->
    <ShipmentDetailDrawer :visible.sync="detailOpen" :shipment-info="detailForm" />

    <!-- 绑定定位器抽屉 -->
    <el-drawer title="绑定定位器" :visible.sync="bindLocatorOpen" direction="rtl" size="50%">
      <div class="drawer-content">
        <!-- 运单基本信息 -->
        <el-card class="box-card" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span>运单基本信息</span>
          </div>
          <el-row>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">运单编号：</span>
                <span class="value">{{ bindWaybillData.billNo }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">运单状态：</span>
                <dict-tag :options="dict.type.bill_status" :value="bindWaybillData.billStatus" />
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">发货方：</span>
                <span class="value">{{ bindWaybillData.senderName }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">收货方：</span>
                <span class="value">{{ bindWaybillData.receiverName }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">货物名称：</span>
                <span class="value">{{ bindWaybillData.goodsName }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">货物重量：</span>
                <span class="value">{{ bindWaybillData.goodsWeight }}kg</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 可绑定定位器列表 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>选择要绑定的定位器</span>
          </div>
          <el-table :data="availableLocators" style="width: 100%" max-height="600"
            @current-change="handleLocatorSelection" ref="locatorTable" highlight-current-row
            v-loading="locatorsLoading">
            <el-table-column type="index" width="55" align="center" label="序号" />
            <el-table-column prop="locatorCode" label="定位器编码" width="150" />
            <el-table-column prop="deviceModel" label="设备型号" width="120" />
            <el-table-column prop="batteryLevel" label="电池电量(%)" width="100" align="center" />
            <el-table-column prop="signalStrength" label="信号强度" width="100" align="center" />
            <el-table-column prop="lastOnlineTime" label="最后在线时间" width="150" align="center">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.lastOnlineTime, '{y}-{m}-{d} {h}:{i}') }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="locatorStatus" label="定位器状态" width="100" align="center">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.device_status" :value="scope.row.locatorStatus" />
              </template>
            </el-table-column>
          </el-table>

          <div style="margin-top: 20px; text-align: center;">
            <el-button @click="bindLocatorOpen = false">取 消</el-button>
            <el-button type="primary" @click="confirmBindLocator" :disabled="!selectedLocator">确认绑定</el-button>
          </div>
        </el-card>


      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listShipment, getShipment, addShipment, updateShipment, delShipment, delShipmentBatch, exportShipment } from '@/api/logistics/shipment'
import { getUnboundLocators } from '@/api/pack/locator'
import { bindLocator, unbindLocator } from '@/api/system/waybill'

import {
  ShipmentSearchForm,
  ShipmentToolbar,
  ShipmentTable,
  ShipmentFormDrawer,
  ShipmentDetailDrawer
} from './components'

export default {
  name: 'Shipment',
  dicts: ['bill_status', 'transport_type'],
  components: {
    ShipmentSearchForm,
    ShipmentToolbar,
    ShipmentTable,
    ShipmentFormDrawer,
    ShipmentDetailDrawer
  },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运单表格数据
      shipmentList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 是否显示绑定定位器抽屉
      bindLocatorOpen: false,
      // 绑定运单数据
      bindWaybillData: {},
      // 可绑定的定位器列表
      availableLocators: [],
      // 定位器列表加载状态
      locatorsLoading: false,
      // 选中的定位器
      selectedLocator: null,


      // 操作模式：add-新增，edit-修改
      mode: 'add',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billNo: undefined,
        billStatus: undefined,
        senderName: undefined,
        receiverName: undefined,
        beginTime: undefined,
        endTime: undefined,
        sortField: undefined,
        sortOrder: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        billNo: undefined,
        billStatus: '1', // 默认待发货

        // 发货信息
        senderName: undefined,
        contactA: undefined,
        phoneA: undefined,
        addressA: undefined,
        coordinatesA: undefined,

        // 收货信息
        receiverName: undefined,
        contactB: undefined,
        phoneB: undefined,
        addressB: undefined,
        coordinatesB: undefined,

        // 货物信息
        goodsName: undefined,
        goodsType: undefined,
        goodsWeight: undefined,
        weightUnit: 'kg',
        volume: undefined,
        transportType: undefined,
        carriage: undefined,
        sendTime: undefined,
        arriveTime: undefined,
        payType: undefined,

        // 备注
        remark: undefined
      },
      // 详情表单
      detailForm: {},
      // 表单校验
      rules: {
        billNo: [
          { required: true, message: '运单编号不能为空', trigger: 'blur' }
        ],
        senderName: [
          { required: true, message: '发货方不能为空', trigger: 'blur' }
        ],
        contactA: [
          { required: true, message: '发货联系人不能为空', trigger: 'blur' }
        ],
        phoneA: [
          { required: true, message: '发货联系电话不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        addressA: [
          { required: true, message: '发货地址不能为空', trigger: 'blur' }
        ],
        senderProvince: [
          { required: true, message: '请在地图上选择发货地址获取省市区信息', trigger: 'change' }
        ],
        senderCity: [
          { required: true, message: '请在地图上选择发货地址获取省市区信息', trigger: 'change' }
        ],
        senderDistrict: [
          { required: true, message: '请在地图上选择发货地址获取省市区信息', trigger: 'change' }
        ],
        receiverName: [
          { required: true, message: '收货方不能为空', trigger: 'blur' }
        ],
        contactB: [
          { required: true, message: '收货联系人不能为空', trigger: 'blur' }
        ],
        phoneB: [
          { required: true, message: '收货联系电话不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        addressB: [
          { required: true, message: '收货地址不能为空', trigger: 'blur' }
        ],
        receiverProvince: [
          { required: true, message: '请在地图上选择收货地址获取省市区信息', trigger: 'change' }
        ],
        receiverCity: [
          { required: true, message: '请在地图上选择收货地址获取省市区信息', trigger: 'change' }
        ],
        receiverDistrict: [
          { required: true, message: '请在地图上选择收货地址获取省市区信息', trigger: 'change' }
        ],
        goodsName: [
          { required: true, message: '货物名称不能为空', trigger: 'blur' }
        ],
        goodsWeight: [
          { required: true, message: '货物重量不能为空', trigger: 'blur' },
          { type: 'number', message: '货物重量必须为数字', trigger: 'blur' }
        ],
        transportType: [
          { required: true, message: '运输方式不能为空', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    /** 删除按钮是否禁用 */
    deleteDisabled () {
      // 如果没有选中任何运单，则禁用删除按钮
      if (!this.ids || this.ids.length === 0) {
        return true
      }

      // 检查选中的运单是否都是"待发货"状态
      const selectedWayBills = this.shipmentList.filter(item => this.ids.includes(item.id))
      const hasNonPendingWayBills = selectedWayBills.some(item =>
        item.billStatus !== '待发货' && item.billStatus !== '1'
      )

      // 如果有非"待发货"状态的运单，则禁用删除按钮
      return hasNonPendingWayBills
    }
  },
  created () {
    this.getList()
  },
  methods: {
    /** 查询运单列表 */
    getList () {
      this.loading = true

      // 准备查询参数，将排序条件转换为字符串
      const params = { ...this.queryParams }
      if (params.sortField && params.sortOrder) {
        // 将排序条件转换为字符串格式: "column1:asc,column2:desc"
        params.sortColumnsStr = `${params.sortField}:${params.sortOrder}`
        delete params.sortField // 删除原始的复杂对象
        delete params.sortOrder // 删除原始的复杂对象
      }

      console.log('发送查询参数:', params)

      listShipment(params).then(response => {
        this.shipmentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,
        billNo: undefined,
        billStatus: '待发货', // 默认待发货

        // 发货信息
        senderName: undefined,
        contactA: undefined,
        phoneA: undefined,
        addressA: undefined,
        coordinatesA: undefined,
        senderProvince: undefined,
        senderCity: undefined,
        senderDistrict: undefined,

        // 收货信息
        receiverName: undefined,
        contactB: undefined,
        phoneB: undefined,
        addressB: undefined,
        coordinatesB: undefined,
        receiverProvince: undefined,
        receiverCity: undefined,
        receiverDistrict: undefined,
        receiverLongitude: undefined,
        receiverLatitude: undefined,

        // 货物信息
        goodsName: undefined,
        goodsType: undefined,
        goodsWeight: undefined,
        weightUnit: '千克(Kg)',
        volume: undefined,
        transportType: undefined,
        carriage: undefined,
        sendTime: undefined,
        arriveTime: undefined,
        payType: undefined,
        // 备注
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange (selection) {
      if (selection.length > 0) {
        this.form = JSON.parse(JSON.stringify(selection[0]))
      }
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      this.open = true
      this.title = '添加运单'
      this.mode = 'add'
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      //this.form = JSON.parse(JSON.stringify(row))
      this.open = true
      this.title = '修改运单'
      this.mode = 'edit'
    },
    /** 提交按钮 */
    submitForm (submitData) {
      console.log('提交表单数据:', submitData || this.form) // 调试日志

      // 获取实际的表单数据和操作模式
      const formData = submitData ? submitData.data : this.form
      const operationMode = submitData ? submitData.mode : (this.form.id ? 'edit' : 'add')

      if (operationMode === 'edit' || this.form.id) {
        // 修改
        updateShipment(formData).then(response => {
          this.$modal.msgSuccess('修改成功')
          this.open = false
          this.getList()
        }).catch(error => {
          console.error('修改失败:', error)
          this.$modal.msgError('修改失败：' + (error.msg || '未知错误'))
        })
      } else {
        // 新增
        addShipment(formData).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        }).catch(error => {
          console.error('新增失败:', error)
          this.$modal.msgError('新增失败：' + (error.msg || '未知错误'))
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      // 确定要删除的ID列表
      let idsToDelete = []
      if (row && row.id) {
        // 单个删除
        idsToDelete = [row.id]
      } else if (this.ids && this.ids.length > 0) {
        // 批量删除
        idsToDelete = [...this.ids]
      }

      // 检查要删除的运单状态
      let wayBillsToDelete = []
      if (row && row.id) {
        // 单个删除
        wayBillsToDelete = [row]
      } else if (this.ids && this.ids.length > 0) {
        // 批量删除，从当前列表中查找对应的运单
        wayBillsToDelete = this.shipmentList.filter(item => this.ids.includes(item.id))
      }

      // 检查运单状态，只允许删除"待发货"状态的运单
      const invalidWayBills = wayBillsToDelete.filter(item =>
        item.billStatus !== '待发货' && item.billStatus !== '1'
      )

      if (invalidWayBills.length > 0) {
        const invalidBillNos = invalidWayBills.map(item => item.billNo).join(', ')
        this.$modal.msgError(`以下运单状态不是'待发货'，不允许删除：${invalidBillNos}`)
        return
      }

      this.$modal.confirm('是否确认删除选中的运单数据项?').then(() => {
        // 根据idsToDelete类型调用不同的API
        if (idsToDelete.length > 1) {
          return delShipmentBatch(idsToDelete.join(','))
        } else {
          return delShipment(idsToDelete[0])
        }
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch((error) => {
        console.error('删除失败:', error)
        this.$modal.msgError('删除失败：' + (error.msg || '未知错误'))
      })
    },
    /** 导出按钮操作 */
    handleExport () {
      // 准备导出参数
      const exportParams = {
        ...this.queryParams,
        pageNum: undefined,  // 导出时不需要分页参数
        pageSize: undefined
      }

      // 处理排序参数
      if (exportParams.sortField && exportParams.sortOrder) {
        exportParams.sortColumnsStr = `${exportParams.sortField}:${exportParams.sortOrder}`
        delete exportParams.sortField
        delete exportParams.sortOrder
      }

      // 如果有选中的行，则导出选中的数据
      if (this.ids && this.ids.length > 0) {
        exportParams.ids = this.ids
        this.$modal.confirm(`是否确认导出选中的${this.ids.length}条运单数据?`).then(() => {
          this.performExport(exportParams, `选中运单数据(${this.ids.length}条)`)
        }).catch(() => { })
      } else {
        // 没有选中数据，导出全部或过滤后的数据
        const hasFilters = this.queryParams.billNo || this.queryParams.billStatus ||
          this.queryParams.senderName || this.queryParams.receiverName ||
          this.queryParams.beginTime || this.queryParams.endTime ||
          this.queryParams.sortField

        let confirmMsg = '是否确认导出所有运单数据?'
        let description = '全部运单数据'

        if (hasFilters) {
          confirmMsg = '是否确认导出当前查询条件下的所有运单数据?'
          description = '筛选条件运单数据'

          // 构建过滤条件描述
          const filters = []
          if (this.queryParams.billNo) filters.push(`运单号包含"${this.queryParams.billNo}"`)
          if (this.queryParams.billStatus) filters.push(`状态为"${this.queryParams.billStatus}"`)
          if (this.queryParams.senderName) filters.push(`发货方包含"${this.queryParams.senderName}"`)
          if (this.queryParams.receiverName) filters.push(`收货方包含"${this.queryParams.receiverName}"`)
          if (this.queryParams.beginTime) filters.push(`创建时间从"${this.queryParams.beginTime}"`)
          if (this.queryParams.endTime) filters.push(`创建时间到"${this.queryParams.endTime}"`)
          if (this.queryParams.sortField) filters.push(`按"${this.queryParams.sortField}"排序`)

          if (filters.length > 0) {
            confirmMsg += `\n\n当前过滤条件：\n${filters.join('\n')}`
          }
        }

        this.$modal.confirm(confirmMsg).then(() => {
          this.performExport(exportParams, description)
        }).catch(() => { })
      }
    },

    /** 执行导出操作 */
    performExport (exportParams, description) {
      this.exportLoading = true
      console.log('导出参数:', exportParams)

      exportShipment(exportParams).then(response => {
        // 检查响应数据
        if (!response) {
          throw new Error('导出响应为空')
        }

        const filename = `${description}_${this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
        console.log('准备下载文件:', filename)

        // 使用下载插件处理Excel文件
        this.$download.excel(response, filename)
      }).catch(error => {
        console.error('导出失败:', error)
        let errorMsg = '导出失败'

        if (error.response) {
          // 服务器响应错误
          errorMsg += `: ${error.response.status} ${error.response.statusText}`
        } else if (error.message) {
          // 其他错误
          errorMsg += `: ${error.message}`
        }

        this.$modal.msgError(errorMsg)
      }).finally(() => {
        this.exportLoading = false
      })
    },
    /** 详情按钮操作 */
    handleDetail (row) {
      this.detailForm = row
      this.detailOpen = true
    },
    /** 排序变化 */
    handleSortChange (column) {
      console.log('排序变化，列信息:', column)

      if (column.order) {
        // 设置排序字段和方向
        this.queryParams.sortField = column.prop
        this.queryParams.sortOrder = column.order === 'ascending' ? 'asc' : 'desc'
        console.log(`设置排序：字段=${column.prop}, 方向=${this.queryParams.sortOrder}`)
      } else {
        // 清除排序
        this.queryParams.sortField = undefined
        this.queryParams.sortOrder = undefined
        console.log('清除排序')
      }

      console.log('当前排序状态:', {
        field: this.queryParams.sortField,
        order: this.queryParams.sortOrder
      })

      // 重置页码并重新查询
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 绑定定位器按钮操作 */
    handleBindLocator (row) {
      console.log('绑定定位器，运单信息:', row)
      this.bindWaybillData = row
      this.selectedLocator = null
      this.bindLocatorOpen = true
      this.loadAvailableLocators()
    },
    /** 加载可绑定的定位器列表 */
    loadAvailableLocators () {
      this.locatorsLoading = true
      // 查询未绑定的定位器（状态为正常且container_id为null、0或-1）
      getUnboundLocators().then(response => {
        this.availableLocators = response.data || []
        console.log('可绑定定位器列表:', this.availableLocators)
      }).catch(error => {
        console.error('加载定位器列表失败:', error)
        this.$modal.msgError('加载定位器列表失败')
        this.availableLocators = []
      }).finally(() => {
        this.locatorsLoading = false
      })
    },
    /** 定位器选择变化（单选模式） */
    handleLocatorSelection (currentRow) {
      this.selectedLocator = currentRow
      console.log('选中定位器:', currentRow)
    },
    /** 确认绑定定位器 */
    confirmBindLocator () {
      if (!this.selectedLocator) {
        this.$modal.msgError('请选择要绑定的定位器')
        return
      }

      const waybillId = this.bindWaybillData.id
      const locatorId = this.selectedLocator.locatorId
      const locatorCode = this.selectedLocator.locatorCode

      console.log('执行绑定操作:', { waybillId, locatorId, locatorCode })

      bindLocator(waybillId, locatorId, locatorCode).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess('绑定成功')
          this.bindLocatorOpen = false // 关闭抽屉
          this.getList() // 刷新运单列表
          this.selectedLocator = null // 清空选择
        } else {
          this.$modal.msgError(response.msg || '绑定失败')
        }
      }).catch(error => {
        console.error('绑定异常:', error)
        this.$modal.msgError('绑定异常')
      })
    },



    /** 解绑定位器按钮操作 */
    handleUnbindLocator (row) {
      console.log('解绑定位器，运单信息:', row)

      // 弹出确认对话框
      this.$modal.confirm('是否确认解除运单与定位器的绑定？').then(() => {
        const waybillId = row.id
        console.log('执行解绑操作，运单ID:', waybillId)

        if (!waybillId) {
          this.$modal.msgError('运单ID不能为空')
          return
        }

        if (!row.locatorId || row.locatorId === 0) {
          this.$modal.msgError('该运单未绑定定位器')
          return
        }

        // 调用运单解绑接口
        unbindLocator(waybillId).then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess('解绑成功')
            this.getList() // 刷新运单列表
          } else {
            this.$modal.msgError(response.msg || '解绑失败')
          }
        }).catch(error => {
          console.error('解绑异常:', error)
          this.$modal.msgError('解绑异常：' + (error.msg || '未知错误'))
        })
      }).catch(() => {
        // 用户取消操作
      })
    }
  }
}
</script>

<style scoped>
.drawer-content {
  padding: 20px;
}

.info-item {
  margin-bottom: 10px;
}

.info-item .label {
  font-weight: bold;
  color: #606266;
}

.info-item .value {
  color: #303133;
}

.box-card {
  margin-bottom: 20px;
}
</style>
